//
//  Status.swift
//  WeiBoOfSwift
//
//  Created by aven wu on 25/04/2018.
//  Copyright © 2018 GML. All rights reserved.
//

import UIKit
import SDWebImage

class Status:NSObject{
    
    var  rowHeight:CGFloat?
    
    /// 微博创建时间
   @objc var created_at: String?
    {
        didSet{
            //  created_at = "Sun Sep 12 14:50:57 +0800 2014"
            // 1.将字符串转换为时间
            let createdDate = NSDate.dateWithStr(time: created_at!)
            // 2.获取格式化之后的时间字符串
            created_at = createdDate.descDate
        }
    }
    /// 微博ID
   @objc var id: Int = 0
    /// 微博信息内容
   @objc var text: String?
    /// 微博来源
    @objc var source: String?
        {
        didSet{
            // <a href=\"http://app.weibo.com/t/feed/4fuyNj\" rel=\"nofollow\">即刻笔记</a>
            print("---------ccccccccccccc\(source)")
            // 1.截取字符串
            if let str = source
            {
                if str.contains("<a href="){
                    // 1.1获取开始截取的位置
                    let startLocation = str.range(of: ">")
                    // 1.2获取结束截取的位置
                    let endLocation = str.range(of: "</a>")
                    
                    let afterRange = str[startLocation!.upperBound ..< endLocation!.lowerBound]
                    // 1.3截取字符串
                    source = "来自:" + afterRange
                }
            }
        }
    }
    /// 配图数组
    @objc var pic_urls: [[String: Any]]?{
        didSet{
            // 1.初始化数组
            storedPicURLS = [NSURL]()
            storedLargePicURLS = [NSURL]()

            // 2遍历取出所有的图片路径字符串
            for dict in pic_urls!
            {
                if let urlStr = dict["thumbnail_pic"] as? String
                {
                    // 将字符串转换为URL保存到数组中
                    storedPicURLS?.append(NSURL(string: urlStr as! String)!)
                    // 2.处理大图
                    let largeURLStr =  urlStr.replacingOccurrences(of: "thumbnail", with: "large")
                    storedLargePicURLS?.append(NSURL(string: largeURLStr)!)
                    print("largeURLStr = \(largeURLStr)")
                }
            }
            
        }
    }
    /// 保存当前微博所有配图的URL
    var storedPicURLS: [NSURL]?
    /// 保存当前微博所有配图"大图"的URL
    var storedLargePicURLS: [NSURL]?
    
    // 用户信息
   @objc var user:UserBaseModel?
    
    /// 转发微博
   @objc var retweeted_status: Status?
    
    // 如果有转发, 原创就没有配图
    /// 定义一个计算属性, 用于返回原创获取转发配图的URL数组
    var pictureURLS:[NSURL]?
    {
        return retweeted_status != nil ? retweeted_status?.storedPicURLS : storedPicURLS
    }
    /// 定义一个计算属性, 用于返回原创或者转发配图的大图URL数组
    var LargePictureURLS:[NSURL]?
    {
        return retweeted_status != nil ? retweeted_status?.storedLargePicURLS : storedLargePicURLS
    }
    
    /// 加载微博数据
    // 通过闭包将返回值传给调用者
    class func loadStatuses(since_id: Int,finished: @escaping(_ models:[Status]?, _ error:NSError?)->()){
        let path = "2/statuses/home_timeline.json"
        var params = ["access_token": UserOauthModel.readAccount()!.access_token!]
        
        // 下拉刷新
        if since_id > 0
        {
            params["since_id"] = "\(since_id)"
        }
        
        NetWorkTools.shareNetWorkTools().get(path, parameters: params, progress: nil, success: { (task, result) in
        // 1.取出statuses key对应的数组 (存储的都是字典)
            let dic = result as? [String:Any]
            let list = dic!["statuses"]
//            print(list)
            // 2.遍历数组, 将字典转换为模型
            let models = dict2Model(list: dic!["statuses"] as? [[String: Any]])
            // 3 缓存微博配图  以便计算图片大小
            cacheStatusImages(list: models!, finished: finished)
            
            finished(models, nil)
        }) { (task, error) in
            print(error)
            finished(nil, error as NSError)

        }
    }
    
    class func cacheStatusImages(list:[Status],finished: @escaping (_ models:[Status]?, _ error:NSError?)->()) -> Void {
        // 1.创建一个组
        let group = DispatchGroup()
        
        for status in list {
            //
            guard status.pictureURLS != nil else {
                continue
            }
            
            for imageUrl in status.pictureURLS! {
                // 进入到当前线程组
                group.enter()
                // 将当前的
                SDWebImageManager.shared().loadImage(with: imageUrl as URL, options: SDWebImageOptions.init(rawValue: 0), progress: nil, completed: { (image, dataImage, error, _, _, _ ) in
                    // 离开当前线程组
                    group.leave()
                })
            }
        }
        // 2.当所有图片都下载完毕再通过闭包通知调用者
        group.notify(queue: DispatchQueue.main) {
            // 能够来到这个地方, 一定是所有图片都下载完毕
            finished(list, nil)
        }
        
    }
    /// 将字典数组转换为模型数组
    class func dict2Model(list: [[String: Any]]?) -> [Status]? {
        if ((list?.count) != nil) {
            var models = [Status]()
            for dict in list!
            {
                models.append(Status(dict: dict))
            }
            return models
        }
        return nil
    }
    // 字典转模型
    init(dict: [String: Any])
    {
        super.init()
        setValuesForKeys(dict)
    }
    // setValuesForKeys(dict)方法会调用 setValue
    override func setValue(_ value: Any?, forKey key: String) {
        // 1.判断当前是否正在给微博字典中的user字典赋值
        if "user" == key
        {
            // 2.根据user key对应的字典创建一个模型
            user = UserBaseModel(dict: value as! [String : AnyObject])
            return
        }
        
        // 2.判断是否是转发微博, 如果是就自己处理
        if "retweeted_status" == key
        {
            retweeted_status = Status(dict: value as! [String : AnyObject])
            return
        }
        // 3,调用父类方法, 按照系统默认处理
        super.setValue(value, forKey: key)
    }
    
    override func setValue(_ value: Any?, forUndefinedKey key: String) {
        
    }
    
    // 打印当前模型
    var properties = ["created_at", "id", "text", "source", "pic_urls"]
    override var description: String {
        let dict = dictionaryWithValues(forKeys: properties)
        return "\(dict)"
    }

    
}
